/* eslint-disable react/sort-comp */
import React from 'react';
import {injectIntl, language} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Card, Spin, message, Table, Popconfirm} from 'antd';
import routes from './routes';
import {FORM_BIG_OPTIONS, FORM_OPTIONS, FORM_ROW_OPTIONS, TABLE, PAGE, FIXED_COLUMN_WIDTH} from '../constants';
import {formatAmount, conventEnumValueToString} from '../utils';
import {PERMISSION, dealerConditions} from './constants';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import FileUpload from './FileUpload';
import {validateAdd} from './utils';
import Return from '../common/Return';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import ClaimApply from './ClaimApply';
import {expenseAdjustmentBillSourceType, expenseAdjustmentDirection, currency} from '../Enum';
import InputAmount from '../common/InputAmount';
import {getDealerSimple, getDealers, getClaimDetail} from './api';
const FormItem = Form.Item;
const autosize = {minRows: 1};
const EMPTY_ARRAY = [];
const EMPTY_OBJECT = {};
const sourceTypes = expenseAdjustmentBillSourceType.pick([
    expenseAdjustmentBillSourceType.维修索赔单,
    expenseAdjustmentBillSourceType.其他
]);

export class Add extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        isDealerFirst: true,
        isBrandFirst: true,
        showPanel: false,
    };
    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }
    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }
    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };
    handleDealerChange = (data = EMPTY_OBJECT) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(this.state.isDealerFirst && !this.props.id) {
            this.setState({
                isDealerFirst: false
            });
            return this.props.onSelectDealer(data);
        }
        const {dealerId} = this.props.conditions;
        if(dealerId === data.id) return;
        Modal.confirm({
            title: this.props.intl.formatMessage({
                id: 'add.handleDealerChange.title',
                defaultMessage: '变更服务站，将会清空扣补款数据，是否清空？'
            }),
            onOk: () => {
                this.props.onSelectDealer(data);
            }
        });
    }
    handleBrandChange = value => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        if(this.state.isBrandFirst && !this.props.id) {
            this.setState({
                isBrandFirst: false
            });
            return this.props.onSelectBrand(value);
        }
        const {brandId} = this.props.conditions;
        if(brandId === value) return;
        Modal.confirm({
            title: this.props.intl.formatMessage({
                id: 'add.handleBrandChange.title',
                defaultMessage: '变更品牌，将会清空扣补款数据，是否清空？'
            }),
            onOk: () => {
                this.props.onSelectBrand(value);
            }
        });
    }
    handleClaimChange = data => {
        this.setState({
            showPanel: false
        });
        if(data.length)
            this.props.onSelectDetails(data);
    }
    handleTypeChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        const {sourceType} = this.props.conditions;
        if(sourceType === value) return;
        if(sourceType)
            Modal.confirm({
                title: this.props.intl.formatMessage({
                    id: 'add.handleTypeChange.title',
                    defaultMessage: '变更源单据，将会清空源单据编号和费用信息，是否清空？'
                }),
                onOk: () => {
                    this.props.onSelectType(name, value);
                }
            });
        else
            this.props.onSelectType(name, value);
    }
    onChangeUpload = data => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.updateAttachments(data);
    }
    renderFee = () => {
        const {sourceType, laborFee = 0, materialFee = 0, mgmtFee = 0, otherFee = 0, assistantFee = 0, adjustmentFee = 0, details} = this.props.conditions;
        //工时费
        let labor = 0;
        //材料费
        let material = 0;
        //管理费
        let mgmt = 0;
        //管理费
        let assistant = 0;
        //其他费用
        let other = 0;
        //费用合计
        let total = 0;

        if(sourceType === expenseAdjustmentBillSourceType.维修索赔单)
            details.forEach(d => {
                labor += d.laborFee;
                material += d.materialFee;
                mgmt += d.mgmtFee;
                other += d.otherFee;
                assistant += d.assistantFee;
            });
        if(sourceType === expenseAdjustmentBillSourceType.维修索赔单)
            total = labor + material + mgmt + assistant + other;
        else
            total = laborFee + otherFee + materialFee + mgmtFee + assistantFee;
        const repairFees = (<React.Fragment>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.laborFee',
                        defaultMessage: '工时费'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {this.props.conditions.sourceType && this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                        ? <InputAmount
                            min={0}
                            name="laborFee"
                            value={laborFee}
                            onBlur={this.handleFilterChange} /> : formatAmount(labor)}
                </FormItem>
            </Col>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.materialFee',
                        defaultMessage: '材料费'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {this.props.conditions.sourceType && this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                        ? <InputAmount
                            min={0}
                            name="materialFee"
                            value={materialFee}
                            onBlur={this.handleFilterChange} /> : formatAmount(material)}
                </FormItem>
            </Col>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.mgmtFee',
                        defaultMessage: '管理费'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {this.props.conditions.sourceType && this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                        ? <InputAmount
                            min={0}
                            name="mgmtFee"
                            value={mgmtFee}
                            onBlur={this.handleFilterChange} /> : formatAmount(mgmt)}
                </FormItem>
            </Col>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.otherFee',
                        defaultMessage: '其他费用'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {this.props.conditions.sourceType && this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                        ? <InputAmount
                            min={0}
                            name="otherFee"
                            value={otherFee}
                            onBlur={this.handleFilterChange} /> : formatAmount(other)}
                </FormItem>
            </Col>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.assistantFee',
                        defaultMessage: '辅料费用'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {this.props.conditions.sourceType && this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                        ? <InputAmount
                            min={0}
                            name="assistantFee"
                            value={assistantFee}
                            onBlur={this.handleFilterChange} /> : formatAmount(assistant)}
                </FormItem>
            </Col>
            <Col {...FORM_OPTIONS.col}>
                <FormItem
                    label={this.props.intl.formatMessage({
                        id: 'add.form.adjustmentFee',
                        defaultMessage: '扣补款金额'
                    })}
                    {...FORM_OPTIONS.item}
                    required>
                    {formatAmount(total)}
                </FormItem>
            </Col>
        </React.Fragment>);
        return repairFees;
    }
    onClickAddBtn = () => {
        this.setState({showPanel: true});
    }
    onCloseClaim = () => {
        this.setState({showPanel: false});
    }
    onSubmit = () => {
        const result = validateAdd(this.props.conditions);
        if(result) {
            this.setState({
                isValidate: true
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    onClickDelete = id => {
        this.props.onDeleteDetail(id);
    };
    onDeleteAll = () => {
        this.props.onDeleteAll();
    }
    onBlurChange = (value, name, id) => {
        this.props.updateDetail({
            [name]: value,
            sourceId: id
        });
    }
    render() {
        const {brandId, dealerId, dealerCode, dealerName, attachments = [], details = []} = this.props.conditions;
        const feeComp = this.renderFee();
        const dealerInfo = dealerId ? {
            id: dealerId,
            code: dealerCode,
            name: dealerName
        } : null;
        const dealerQuery = {
            ...dealerConditions,
            brandId: this.props.conditions.brandId,
        };
        const dealerComp = this.props.conditions.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealerSimple}
            getDealers={getDealers}
            conditions={dealerQuery}
            onSelect={this.handleDealerChange} />) : (<TextInput name="dealerId"
            value={''} disabled placeholder={this.props.intl.formatMessage({
                id: 'add.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.sourceCode',
                    defaultMessage: '源单据编号'
                }),
                dataIndex: 'sourceCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.productCategoryCode',
                    defaultMessage: '车型'
                }),
                dataIndex: 'productCategoryCode'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.laborFee',
                    defaultMessage: '工时费'
                }),
                dataIndex: 'laborFee',
                render: (text, record) => {
                    const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                min={0}
                                precision={2}
                                value={text} onBlur={value => this.onBlurChange(value, 'laborFee', record.sourceId)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.materialFee',
                    defaultMessage: '材料费'
                }),
                dataIndex: 'materialFee',
                render: (text, record) => {
                    const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                min={0}
                                id={record.sourceId}
                                precision={2}
                                value={text} onBlur={value => this.onBlurChange(value, 'materialFee', record.sourceId)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.mgmtFee',
                    defaultMessage: '管理费'
                }),
                dataIndex: 'mgmtFee',
                render: (text, record) => {
                    const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                min={0}
                                id={record.sourceId}
                                precision={2}
                                value={text} onBlur={value => this.onBlurChange(value, 'mgmtFee', record.sourceId)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.otherFee',
                    defaultMessage: '其他费用'
                }),
                dataIndex: 'otherFee',
                render: (text, record) => {
                    const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                min={0}
                                id={record.sourceId}
                                precision={2}
                                value={text} onBlur={value => this.onBlurChange(value, 'otherFee', record.sourceId)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.assistantFee',
                    defaultMessage: '辅料费用'
                }),
                dataIndex: 'assistantFee',
                render: (text, record) => {
                    const validate = (text === null || text === undefined) ? {validateStatus: 'error'} : null;
                    return (
                        <FormItem {...validate}>
                            <InputAmount
                                min={0}
                                id={record.sourceId}
                                precision={2}
                                value={text} onBlur={value => this.onBlurChange(value, 'assistantFee', record.sourceId)}/>
                        </FormItem>
                    );
                }
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'add.column.totalFee',
                    defaultMessage: '金额合计'
                }),
                dataIndex: 'totalFee',
                render: (text, record) => formatAmount(record.laborFee + record.materialFee + record.mgmtFee + record.otherFee + record.assistantFee)
            },
            {
                title:
                details && details.length > 0 ? (
                    <Popconfirm placement="topRight" title={this.props.intl.formatMessage({
                        id: 'add.column.column.allDelete',
                        defaultMessage: '是否确认全部删除？'
                    })} onConfirm={this.onDeleteAll} >
                        <a>{this.props.intl.formatMessage({
                            id: 'add.column.column.empty',
                            defaultMessage: '清空'
                        })}</a>
                    </Popconfirm>
                ) : (
                    <a>
                        {this.props.intl.formatMessage({
                            id: 'add.column.clear',
                            defaultMessage: '清空'
                        })}
                    </a>
                ),
                dataIndex: 'sourceId',
                fixed: 'right',
                width: FIXED_COLUMN_WIDTH,
                render: text => (
                    <a data-id={text} onClick={() => this.onClickDelete(text)}>
                        {this.props.intl.formatMessage({
                            id: 'btn.delete',
                            defaultMessage: '删除'
                        })}
                    </a>
                )
            }
        ];
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.expenseAdjustment.title',
                                defaultMessage: '扣补款信息'
                            })}>
                            <Row>
                                <Col key="code" {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '扣补款单号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.id ? this.props.conditions.code : this.props.intl.formatMessage({
                                            id: 'add.form.code.noData',
                                            defaultMessage: '<尚未生成>'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                {this.props.brands ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                        required>
                                        {this.props.id
                                            ? <span className="value-font">{`(${this.props.conditions.brandCode})${this.props.conditions.brandName}`}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleBrandChange} />}
                                    </FormItem>
                                </Col> : null }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !dealerId ? 'error' : null}
                                        required>
                                        {this.props.id ? <span className="value-font">{`(${this.props.conditions.dealerCode})${this.props.conditions.dealerName}`}</span> : dealerComp}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.direction',
                                            defaultMessage: '扣补款方向'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.direction ? 'error' : null}
                                        required>
                                        {this.props.id ? conventEnumValueToString(expenseAdjustmentDirection, this.props.conditions.direction) : <WrappedSelect
                                            name="direction"
                                            value={this.props.conditions.direction}
                                            options={expenseAdjustmentDirection.toList(language)}
                                            onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.sourceType',
                                            defaultMessage: '源单据类型'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.sourceType ? 'error' : null}
                                        required>
                                        {this.props.id ? conventEnumValueToString(sourceTypes, this.props.conditions.sourceType) : <WrappedSelect
                                            disabled={!dealerId || !this.props.conditions.brandId}
                                            placeholder={dealerId && this.props.conditions.brandId ? '' : this.props.intl.formatMessage({
                                                id: 'add.sourceType.placeholder',
                                                defaultMessage: '请先选择服务站和品牌'
                                            })}
                                            name="sourceType"
                                            value={this.props.conditions.sourceType}
                                            options={sourceTypes.toList(language)}
                                            onChange={this.handleTypeChange} />}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.currency',
                                            defaultMessage: '币种'
                                        })}
                                        {...FORM_OPTIONS.item} >
                                        {conventEnumValueToString(currency, this.props.conditions.currency)}
                                    </FormItem>
                                </Col>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.reason',
                                        defaultMessage: '扣补款原因'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}
                                    validateStatus={this.state.isValidate && !this.props.conditions.reason ? 'error' : null}
                                    required>
                                    <TextInput type="textarea" name="reason" autosize={autosize}
                                        value={this.props.conditions.reason} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                            <Row>
                                <FormItem
                                    label={this.props.intl.formatMessage({
                                        id: 'add.form.remark',
                                        defaultMessage: '备注'
                                    })}
                                    {...FORM_ROW_OPTIONS.item}>
                                    <TextInput type="textarea" name="remark" autosize={autosize}
                                        value={this.props.conditions.remark} onBlur={this.handleFilterChange} />
                                </FormItem>
                            </Row>
                        </Card>
                        <Card title={this.props.intl.formatMessage({
                            id: 'add.fee.title',
                            defaultMessage: '费用信息'
                        })}>
                            <Row>
                                {feeComp}
                            </Row>
                        </Card>
                        {!this.props.conditions.sourceType || this.props.conditions.sourceType === expenseAdjustmentBillSourceType.其他
                            ? null : <Card title={this.props.intl.formatMessage({
                                id: 'add.card.fileList.details',
                                defaultMessage: '扣补款单清单'
                            })}
                            extra={<div>
                                <Button
                                    size="small"
                                    onClick={this.onClickAddBtn}>
                                    {this.props.intl.formatMessage({
                                        id: 'add.operation.newDetail',
                                        defaultMessage: '新增清单'
                                    })}
                                </Button>
                            </div>}>
                                <Table
                                    className="white-space-nowrap"
                                    rowKey="sourceId"
                                    columns={columns}
                                    pagination={false}
                                    dataSource={this.props.conditions.details}
                                    {...TABLE}/>
                            </Card>
                        }
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.card.fileList.title',
                                defaultMessage: '扣补款附件'
                            })}
                            className={styles.marginBottom}>
                            <Row>
                                <Col {...FORM_BIG_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload} onRemove={this.props.removeAttachments} fileList={attachments} />
                                </Col>
                            </Row>
                        </Card>
                        {this.props.submitable && (
                            <Card type="inner">
                                <Row>
                                    <Col className="col-align-right">
                                        <Button
                                            key="submit"
                                            loading={this.state.loading}
                                            onClick={this.onSubmit}
                                            type="primary">
                                            {this.props.intl.formatMessage({
                                                id: 'add.btn.submit',
                                                defaultMessage: '保存'
                                            })}
                                        </Button>
                                    </Col>
                                </Row>
                            </Card>
                        )}
                    </Form>
                </Spin>
                {
                    this.state.showPanel &&
                    <ClaimApply
                        selectKey={details.sourceId}
                        brandId={brandId}
                        dealerId={dealerId}
                        onCancel={this.onCloseClaim}
                        currentSelectRowkeys={details}
                        onSelect={this.handleClaimChange} />
                }
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
            </div>
        );
    }
}
Add.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    id: PropTypes.string,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onSubmit,
    selectDealer,
    selectSourceType,
    getEditInit,
    selectBrand,
    selectDetails,
    deleteDetails,
    deleteDetailsAll,
    saveDetails,
    updateAttachments,
    removeAttachments
} from './actions';
import {createSelector} from 'reselect';

import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getSubmitData = selectorFactory(['page', 'appState', 'submitData']);
const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    brands => {
        const data = brands.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            value: item.id,
            text: `(${item.code})${item.name}`
        }));
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrands(state),
    isDealerUser: state.getIn((['page', 'domainData', 'initData', 'isDealerUser'])),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInit(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onSubmit: () =>
        dispatch(onSubmit(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onSelectDealer: data => dispatch(selectDealer(data)),
    onSelectBrand: value => dispatch(selectBrand(value)),
    onSelectType: (name, value) => dispatch(selectSourceType(name, value)),
    onSelectDetails: data => dispatch(selectDetails(data)),
    onDeleteAll: data => dispatch(deleteDetailsAll(data)),
    onDeleteDetail: data => dispatch(deleteDetails(data)),
    updateDetail: data => dispatch(saveDetails(data)),
    updateAttachments: data => dispatch(updateAttachments(data)),
    removeAttachments: ({id}) => dispatch(removeAttachments(id)),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Add));
